import { User } from '@/models/user';
import UserService from '@/services/user';
import { action, computed, observable } from 'mobx';

/**
 * 用户实体Keys
 */
const UserKeys = ['id', 'state', 'username', 'account', 'avatarUrl', 'email'];

/**
 * 用户Store
 */
export default class UserStore {
  @observable
  userInfo?: User;
  @observable
  loading: boolean = false;

  constructor() {
    this.loadLocalStoreage();
  }

  @computed
  get loginState() {
    return this.userInfo?.id != null;
  }

  loadLocalStoreage = () => {
    this.userInfo = {};
    UserKeys.forEach((key) => {
      this.userInfo![key] = localStorage.getItem(key);
    });
  };

  saveLocalStorage = () => {
    UserKeys.forEach((key) => {
      localStorage.setItem(key, (this.userInfo ?? {})[key]);
    });
  };
  removeLocalStorage = () => {
    UserKeys.forEach((key) => {
      localStorage.removeItem(key);
    });
  };

 /**
  *登录
  * @param account 
  * @param pwd 
  * @returns 
  */

  @action
  async login(account: string, pwd: string): Promise<boolean> {
    this.loading = true;
    const result = await UserService.login(account, pwd);
    this.userInfo = result.dataInfo;
    if (result.isSuccess) {
      this.saveLocalStorage();
    }
    this.loading = false;
    return result.isSuccess;
  }
  /**
   * 免密登录
   * @param moblie
   * @param code 验证码
   * @returns
   */
  @action
  async freeLogin(moblie: string, code: string): Promise<boolean> {
    this.loading = true;
    const result = await UserService.freeLogin(moblie, code);
    this.userInfo = result.dataInfo;
    if (result.isSuccess) {
      this.saveLocalStorage();
    }
    this.loading = false;
    return result.isSuccess;
  }

  /**
   * 注册
   * @param code 验证码
   * @param mobile
   * @param pwd
   * @returns
   */
  @action
  async register( account: string, pwd: string): Promise<boolean> {
    this.loading = true;
    const result = await UserService.register(account, pwd);
    this.loading = false;
    return result.isSuccess;
  }

  /**
   * 忘记密码
   * @param code 验证码
   * @param mobile
   * @param pwd
   * @returns
   */
  // @action
  // async forgetPwd(code: string, mobile: string, pwd: string): Promise<boolean> {
  //   this.loading = true;
  //   const result = await UserService.forgetPwd(code, mobile, pwd);
  //   this.loading = false;
  //   return result.isSuccess;
  // }
  /**
   * 用户详情
   * @returns
   */
  @action
  async getUserInfo() {
    const userInfo = await UserService.getUserInfo();
    this.userInfo = userInfo.dataInfo;
    if (userInfo.isSuccess) {
      this.saveLocalStorage();
    }
  }
  /**
   * 退出登录
   *
   */
  @action
  async logout() {
    UserService.logout();
    this.userInfo = undefined;
    this.removeLocalStorage();
  }
}

export const userStore = new UserStore();
